package server.model.goodModel;

import com.alibaba.fastjson.JSON;
import server.db.DBFactory;
import server.util.InfoUtils.Info;
import server.util.InfoUtils.InfoEnum;
import server.util.InfoUtils.InfoUtil;

import java.util.List;

public class JsonIdInUserModel {
    //增加
    public Info addObj2User(String colName, Integer userId, Integer addId) {
        //判断数据库中是否已经收藏
        String getSql = "select json_contains(&,'&') from user where user_id = &";
        String haveObj = DBFactory.getDBDriver().queryOne(getSql, colName, addId.toString(), userId.toString());
        if (haveObj.equals("1")) {
            return InfoUtil.getInfo(1, "已添加过");
        }

        String updateSql = "update user set " + colName + " = json_array_append(" + colName + ",'$',?) where user_id = ?";
        int line = DBFactory.getDBDriver().update(updateSql, addId, userId);
        if (line > 0) {
            return InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
    }

    //删除
    public Info deleteObjInUser(String colName, int userId, Integer delId) {

        String getSql = "select " + colName + " from user where user_id = " + userId;
        String getObj = DBFactory.getDBDriver().queryOne(getSql);
        if (getObj == null) {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
        List<Integer> objs = JSON.parseArray(getObj, Integer.class);
        objs.remove(delId);
        //将objs数列转化为json，存入数据库
        String setObj = JSON.toJSONString(objs);

        String updateSql = "update user set " + colName + "= ? where user_id = ?";
        int line = DBFactory.getDBDriver().update(updateSql, setObj, userId);
        if (line > 0) {
            return InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
    }

    public Info addBought(Integer userId, Integer addId) {
        String updateSql = "update user set bought = json_array_append(bought,'$',?) where user_id = ?";
        int line = DBFactory.getDBDriver().update(updateSql, addId, userId);
        if (line > 0) {
            return InfoUtil.getInfo(InfoEnum.SUCCESS);
        } else {
            return InfoUtil.getInfo(InfoEnum.FAIL);
        }
    }
}
